package handlers

import (
	"fmt"
	"gitee.com/hilaoyu/go-basic-utils/utilVnc/types"
)

type VersionHandler struct {
	ClientProtoVersion string // 'RFB 003.008'
}

const protoVersionLength = 12

// ParseProtoVersion parse protocol version
func parseProtoVersion(pv []byte) (uint, uint, error) {
	var major, minor uint

	if len(pv) < protoVersionLength {
		return 0, 0, fmt.Errorf("ProtocolVersion message too short (%v < %v)", len(pv), protoVersionLength)
	}

	l, err := fmt.Sscanf(string(pv), "RFB %d.%d\n", &major, &minor)
	if l != 2 {
		return 0, 0, fmt.Errorf("error parsing protocol version")
	}
	if err != nil {
		return 0, 0, err
	}

	return major, minor, nil
}

func (h *VersionHandler) Handle(c *types.VncConn) error {
	var version [protoVersionLength]byte
	if "" == h.ClientProtoVersion {
		h.ClientProtoVersion = "RFB 003.008"
	}

	if err := c.Read(&version); err != nil {
		return err
	}

	maxMajor, maxMinor, err := parseProtoVersion(version[:])
	if err != nil {
		return err
	}
	if maxMajor < 3 {
		return fmt.Errorf("VersionHandler unsupported major version, less than 3: %d", maxMajor)
	}
	if maxMinor < 8 {
		return fmt.Errorf("VersionHandler unsupported minor version, less than 8: %d", maxMinor)
	}

	if err = c.Write([]byte(h.ClientProtoVersion + "\n")); err != nil {
		return fmt.Errorf("VersionHandler Write version: %s,error", h.ClientProtoVersion, err.Error())
	}

	return nil
}
